package cn.vihub.service.impl;

import cn.vihub.handler.MyRuntimeException;
import cn.vihub.service.TokenService;
import cn.vihub.vo.TokenVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class TokenServiceImpl implements TokenService {

    @Override
    public TokenVo createAccessToken(Integer userId, String username) {

        // 生成登录token
        // 1）创建一个JwtBuilder
        JwtBuilder builder = Jwts.builder();
        // 2）设置密钥（加密算法，密钥一般32位字符串就够了）
        builder.signWith(SignatureAlgorithm.HS256, "34508954965klurtjywr04657");
        // 3）设置token的失效时间（失效的哪个时间点的 Date）
        Long expTime = System.currentTimeMillis() + 7200000;
        builder.setExpiration(new Date(expTime));
        // 4）设置唯一id
        builder.setId(userId+"");
        // 5）设置内容
        builder.claim("userId", userId).claim("username", username);
        // 6）完成
        String token = builder.compact();

        /***********************************************生成refresh_token***********************************************/

        Long refreshExpTime = System.currentTimeMillis() + (86400000*7);
        String refreshToken = Jwts.builder().setId(userId + "").signWith(SignatureAlgorithm.HS256, "34508954965klurtjywr04657")
                .setExpiration(new Date(refreshExpTime))
                .claim("userId", userId).claim("username", username).claim("status", "refresh").compact();


        // 生成刷新用的token
        TokenVo tokenVo = new TokenVo();
        tokenVo.setAccessToken(token);
        tokenVo.setAccessTokenTime(expTime);
        tokenVo.setRefreshToken(refreshToken);
        tokenVo.setRefreshTokenTime(refreshExpTime);

        return tokenVo;
    }

    @Override
    public TokenVo createRefreshToken(String refreshToken) {

        try {
            // 解析token
            Claims body = Jwts.parser().setSigningKey("34508954965klurtjywr04657").parseClaimsJws(refreshToken).getBody();

            // 有效期截至时间
            Date expiration = body.getExpiration();

            // 获取用户id和名称
            Integer userId = (Integer)body.get("userId");
            String username = body.get("username").toString();

            TokenVo tokenVo = createAccessToken(userId, username);
            // 设置refreshtoken为原来的不用新的
            tokenVo.setRefreshToken(refreshToken);
            tokenVo.setRefreshTokenTime(expiration.getTime());

            return tokenVo;
        }catch (Exception e){
            throw new MyRuntimeException("token失效或者非法");
        }

    }
}
